package com.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;

import org.apache.log4j.Logger;
import org.primefaces.model.LazyDataModel;
import org.primefaces.model.SortOrder;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.web.jsf.FacesContextUtils;

import com.builder.ParametroBuilder;
import com.dao.BaseModelDAO;
import com.model.Parametro;
import com.query.ParametroQuery;
import com.util.JSFUtil;
import com.util.ValidatorUtil;
import com.view.ParametroView;

@ManagedBean
@ViewScoped
@SuppressWarnings("serial")
public class ParametroController extends PaginableController<Parametro> {

	private Logger log = Logger.getLogger(ParametroController.class);
	private BaseModelDAO<Parametro> dao;
	private Parametro model;
	private ParametroQuery query;

	@ManagedProperty("#{parametroView}")
	private ParametroView view;

	@ManagedProperty("#{parametroBuilder}")
	private ParametroBuilder builder;

	@SuppressWarnings("unchecked")
	public ParametroController() {

		try {
			dao = (BaseModelDAO<Parametro>) FacesContextUtils
					.getWebApplicationContext(FacesContext.getCurrentInstance())
					.getBean("parametroDAO");
			query = new ParametroQuery();

			addEdit = false;

		} catch (Throwable e) {
			log.error("Error al inicializar la clase ParametroController", e);
			FacesContext.getCurrentInstance().addMessage(
					null,
					new FacesMessage(FacesMessage.SEVERITY_ERROR,
							"Error al realizar la operacion", ""));
		}
	}

	public Parametro getModel() {
		return model;
	}

	public void setModel(Parametro model) {
		this.model = model;
	}

	public ParametroQuery getQuery() {
		return query;
	}

	public void setQuery(ParametroQuery query) {
		this.query = query;
	}

	public ParametroView getView() {
		return view;
	}

	public void setView(ParametroView view) {
		this.view = view;
	}

	public ParametroBuilder getBuilder() {
		return builder;
	}

	public void setBuilder(ParametroBuilder builder) {
		this.builder = builder;
	}

	@Override
	public void query(ActionEvent event) {
		loadList();
	}

	@Override
	public void edit(ActionEvent event) {

		try {
			model = lazyDM.getRowData();
			view = builder.toView(model);
			addEdit = true;
		} catch (Throwable e) {
			log.error("Error al editar", e);
			FacesContext.getCurrentInstance().addMessage(
					null,
					new FacesMessage(FacesMessage.SEVERITY_ERROR,
							"Error al realizar la operacion", ""));
		}

	}

	@Override
	public void delete(ActionEvent event) {

		try {
			model = lazyDM.getRowData();
			dao.delete(model);
			loadList();
		} catch (DataIntegrityViolationException e) {
			JSFUtil.saveMessage(
					"El elemento no puede ser eliminado por estar relacionado con otro elemento del sistema.",
					FacesMessage.SEVERITY_ERROR);
		} catch (Throwable e) {
			log.error("Error al eliminar", e);
			FacesContext.getCurrentInstance().addMessage(
					null,
					new FacesMessage(FacesMessage.SEVERITY_ERROR,
							"Error al realizar la operacion", ""));
		}
	}

	@Override
	public void add(ActionEvent event) {
		clear();

		addEdit = true;
	}

	@Override
	public void save(ActionEvent event) {

		try {
			model = builder.toDomain(view);

			List<String> errores = new ValidatorUtil().validate(view);

			if (errores.size() == 0) {

				if (model.getID() != null) {
					dao.edit(model);
					addEdit = false;
				} else {
					dao.save(model);
				}
				clear();
				JSFUtil.saveMessage("Elemento guardado con exito",
						FacesMessage.SEVERITY_INFO);
				if (!addEdit) {
					loadList();
				}

			} else {
				JSFUtil.saveMessages(errores);
			}

		} catch (Throwable e) {
			log.error("Error al guardar", e);
			FacesContext.getCurrentInstance().addMessage(
					null,
					new FacesMessage(FacesMessage.SEVERITY_ERROR,
							"Error al realizar la operacion", ""));
		}
	}

	@Override
	public void cancel(ActionEvent event) {
		addEdit = false;
		lazyDM = null;
		clear();
	}

	@Override
	public void clear() {
		view = new ParametroView();
		model = new Parametro();
	}

	private void loadList() {

		lazyDM = new LazyDataModel<Parametro>() {
			@Override
			public List<Parametro> load(int first, int pageSize,
					String sortField, SortOrder sortOrder,
					Map<String, Object> filters) {

				Map<String, Object> filtro = new HashMap<String, Object>();
				filtro.put("codigo", query.getCodigo());
				filtro.put("valor", query.getValor());

				return dao.getList(first, pageSize, "codigo", true, filtro,
						true);
			}
		};

		Map<String, Object> filtro = new HashMap<String, Object>();
		filtro.put("codigo", query.getCodigo());
		filtro.put("valor", query.getValor());
		lazyDM.setRowCount(dao.count(filtro, true).intValue());
	}

}
